﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace MVAScratchPad.Services
{
    /// <summary>
    ///     This is a very simple implementation of a messagebus. It does not deal with weak references
    ///     so will cause issues with garbage collection if used in any application of scale and
    ///     the UnRegister method is not used.
    /// </summary>
    public class MessageBus
    {
        private static MessageBus _instance;
        private static readonly object NewLock = new object();
        private static Dictionary<Type, object> _recipients;

        /// <summary>
        ///     Initializes a new instance of the <see cref="T:System.Object" /> class.
        /// </summary>
        /// <remarks>
        ///     Ensures we only have a singleton
        /// </remarks>
        private MessageBus()
        {
            _recipients = new Dictionary<Type, object>();
        }

        public static MessageBus Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (NewLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new MessageBus();
                        }
                    }
                }

                return _instance;
            }
        }

        public void Send<TMessage>(TMessage message) where TMessage : class
        {
            if (_recipients.ContainsKey(typeof (TMessage)))
            {
                var list = _recipients[typeof (TMessage)] as List<RecipientAndAction<TMessage>>;
                if (list != null)
                {
                    foreach (var recipient in list)
                    {
                        recipient.Action(message);
                    }
                }
            }
        }

        public void Register<TMessage>(object recipient, Action<TMessage> action) where TMessage : class
        {
            var recipientAndAction = new RecipientAndAction<TMessage>(recipient, action);
            if (_recipients.ContainsKey(typeof (TMessage)))
            {
                var list = _recipients[typeof (TMessage)] as List<RecipientAndAction<TMessage>>;
                if (list != null)
                {
                    list.Add(recipientAndAction);
                }
            }
            else
            {
                var list = new List<RecipientAndAction<TMessage>> {recipientAndAction};
                _recipients.Add(typeof (TMessage), list);
            }
        }

        public void UnRegister<TMessage>(object recipient) where TMessage : class
        {
            if (_recipients.ContainsKey(typeof(TMessage)))
            {
                var list = _recipients[typeof(TMessage)] as List<RecipientAndAction<TMessage>>;
                var entriesToRemove = new List<RecipientAndAction<TMessage>>();
                if (list != null)
                {
                    entriesToRemove.AddRange(list.Where(recipientAndAction => recipientAndAction.Recipent == recipient));

                    if (entriesToRemove.Any())
                    {
                        foreach (var recipientAndAction in entriesToRemove)
                        {
                            list.Remove(recipientAndAction);
                        }
                    }
                }
            }
        }

        public void Reset()
        {
            _recipients.Clear();
        }
    }

    public class RecipientAndAction<TMessage> where TMessage : class
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="T:System.Object" /> class.
        /// </summary>
        public RecipientAndAction(object recipent, Action<TMessage> action)
        {
            Recipent = recipent;
            Action = action;
        }

        public object Recipent { get; private set; }
        public Action<TMessage> Action { get; private set; }
    }
}